package cn.hfjava.kz.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hfjava.kz.config.properties.KzUploadProperties;
import cn.hfjava.kz.config.properties.WhitelistProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Resource
    private KzUploadProperties kzUploadProperties;


    @Resource
    private  WhitelistProperties whitelistProperties;



    @Bean
    public StpLogic getStpLogicJwt() {
        // Sa-Token 整合 jwt (简单模式)
        return new StpLogicJwtForSimple();
    }



    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }


//    @Bean
//    public ModelMapper modelMapper() {
//        return new ModelMapper();
//    }

    // 注册静态资源处理器
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 设置上传文件保存目录
        registry.addResourceHandler(kzUploadProperties.getAssetsUrl())
                .addResourceLocations("file:" + kzUploadProperties.getUploadPath());
    }


//     注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("用户登录认证拦截器注册成功");
//             注册 Sa-Token 拦截器，定义详细认证规则
            registry.addInterceptor(new SaInterceptor(handler -> {
//                 指定一条 match 规则
                SaRouter
                        .match("/**")    // 拦截的 path 列表，可以写多个 */
                        .notMatch("/api/v1/auth/login")        // 排除掉的 path 列表，可以写多个
                        .notMatch("/swagger-ui/**")
                        .notMatch("/v3/api-docs/**")
                        .notMatch("/swagger-resources/**")
                        .notMatch("/webjars/**")
                        .notMatch("/api/v1/auth/forgetPassword")
                        .notMatch("/api/v1/auth/verifyCode")
                        .notMatch("/api/v1/auth/updatePassword")
                        .check(r -> StpUtil.checkLogin());   })) ;
    }
                // 根据路由划分模块，不同模块不同鉴权
//                SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
//                SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
//                SaRouter.match("/goods/**", r -> StpUtil.checkPermission("goods"));
//                SaRouter.match("/orders/**", r -> StpUtil.checkPermission("orders"));
//                SaRouter.match("/notice/**", r -> StpUtil.checkPermission("notice"));
//                SaRouter.match("/comment/**", r -> StpUtil.checkPermission("comment"));
           // })).addPathPatterns("/**");

   // }



    /**
     * 注册 Sa-Token 路由拦截器
     */
 /*   @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 路由拦截鉴权 - 登录校验
        registry.addInterceptor(new SaInterceptor(r -> {
            StpUtil.checkLogin();
        }).isAnnotation(false)).addPathPatterns("/api/v1/**").
                excludePathPatterns(
                        whitelistProperties.getWhitelist()
                );

        // 打开注解鉴权
        registry.addInterceptor(new SaInterceptor())
                .addPathPatterns("/api/v1/**")
                .excludePathPatterns(whitelistProperties.getWhitelist());
    }*/

    //全局配置跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        //以/api/v1/打头所有请求路径允许跨域访问
        registry.addMapping("/api/v1/**") //    /api/v1/**
                //允许哪些域名进行跨域访问
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")  // axios.get/post/put/delete
                // 设置访问源请求头
                .allowedHeaders("*")  //Origin, X-Requested-With, Authorization,Content-Type, Accept, Connection, User-Agent, Cookie,token
                //指定预检请求的有效期，单位为秒  3600秒=1个小时
                .maxAge(3600L)
                // 是否携带Cookie，默认false
                .allowCredentials(true)
                .exposedHeaders("*");
    }
}
